package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.framework.exception.ServiceException;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.SysDepartmentMapper;
import com.mars.module.admin.mapper.SysDoctorRecordsMapper;
import com.mars.module.admin.mapper.SysHospitalMapper;
import com.mars.module.admin.request.SysVisitRecordsRequest;
import com.mars.module.admin.service.ISysDictDataService;
import com.mars.module.system.entity.SysPost;
import com.mars.module.system.mapper.SysPostMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysDoctorRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysDoctorMapper;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysDoctorService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 医生业务层处理
 *
 * @author caiJin
 * @date 2024-05-09
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysDoctorServiceImpl implements ISysDoctorService {

    private final SysDoctorMapper baseMapper;
    private final SysDepartmentMapper departmentMapper;
    private final SysPostMapper postMapper;
    private final ISysDictDataService iSysDictDataService;
    private final SysDoctorRecordsMapper doctorRecordsMapper;
    private final SysHospitalMapper hospitalMapper;
    private final SysDoctorMapper sysDoctorMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysDoctor add(SysDoctorRequest request) {
        SysDoctor entity = SysDoctor.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setCreateById(userId);
        entity.setIsFree("1");
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysDoctorRequest request) {
        SysDoctor entity = SysDoctor.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysDoctor getById(Long id) {
        SysDoctor doctor = baseMapper.selectById(id);
        SysDepartment department = departmentMapper.selectById(doctor.getDepartmentId());
        SysHospital sysHospital = hospitalMapper.selectById(department.getHospitalId());
        doctor.setFullName(doctor.getName() + "-" + department.getName() + "-" + sysHospital.getName());
        return doctor;
    }

    @Override
    public PageInfo<SysDoctor> pageList(SysDoctorRequest request) {
        Page<SysDoctor> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysDoctor> query = this.buildWrapper(request);
        IPage<SysDoctor> pageRecord = baseMapper.selectPage(page, query);
        List<SysDoctor> records = pageRecord.getRecords();
        List<SysDoctor> recordsNew = new ArrayList<>();
        for (SysDoctor doctor : records) {
            SysDepartment department = departmentMapper.selectById(doctor.getDepartmentId());
            doctor.setDepartmentName(department == null ? "" : department.getName());
            SysPost sysPost = postMapper.selectById(doctor.getPostId());
            doctor.setPostName(sysPost == null ? "" : sysPost.getPostName());
            doctor.setSex(iSysDictDataService.getDictDataById("sex", doctor.getSex()));
            if ("1".equals(doctor.getIsFree())) {
                doctor.setIsFree("是");
            } else if ("0".equals(doctor.getIsFree())) {
                doctor.setIsFree("否");
            }
            SysHospital sysHospital = hospitalMapper.selectById(department.getHospitalId());
            doctor.setFullName(department.getName() + "-" + sysHospital.getName());
            recordsNew.add(doctor);
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysDoctor> list(SysDoctorRequest request) {
        LambdaQueryWrapper<SysDoctor> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public List<SysDoctor> getDoctorList(SysVisitRecordsRequest request) {
        List<SysDoctor> result = new ArrayList<>();
        //1.通过小区名称确定医院
        String hospitalId = iSysDictDataService.getDictSortByVaule("hospital", request.getHome());
        SysHospital sysHospital = hospitalMapper.selectById(hospitalId);
        //2.通过症状确定科室
        List<String> describeList = iSysDictDataService.getDictData("describe").stream()
                .map(SysDictData::getDictValue)
                .collect(Collectors.toList());
        String departmentId = "";
        for (String describe : describeList) {
            if (request.getDisease().contains(describe)) {
                departmentId = iSysDictDataService.getDictSortByVaule("describe", describe);
                break;
            }
        }
        if (StringUtils.isBlank(departmentId)) {
            throw new ServiceException("无法识别症状【" + request.getDisease() + "】");
        }
        //3.判断当前医院是否存在科室
        SysDepartment department = departmentMapper.selectById(departmentId);
        if (department != null) {
            if (!hospitalId.equals(department.getHospitalId().toString())) {
                throw new ServiceException("附近的医院没有" + department.getName());
            } else {
                //4.查询医院的科室中，用户所填时间当天空闲的医生
                List<SysDoctor> doctorList = sysDoctorMapper.selectList(new QueryWrapper<SysDoctor>().eq("department_id", departmentId));
                if (doctorList != null && doctorList.size() > 0) {
                    for (SysDoctor doctor : doctorList) {
                        Long l = doctorRecordsMapper.selectCount(new QueryWrapper<SysDoctorRecords>().eq("doctor_id", doctor.getId())
                                .eq("visit_date", request.getVisitDate()));
                        if (l == 0) {
                            //不存在出诊记录则说明医生空闲
                            doctor.setFullName(doctor.getName() + "-" + department.getName() + "-" + sysHospital.getName());
                            result.add(doctor);
                        }
                    }
                }
            }
        } else {
            throw new ServiceException("没有找到症状【" + request.getDisease() + "】相关的科室");
        }
        //没有空闲的医生或者附近医院的科室下没有医生则查询其他医院的医生
        if (result == null || result.size() == 0) {
            List<SysDepartment> departmentList = departmentMapper.selectList(new QueryWrapper<SysDepartment>().eq("name", department.getName())
                    .ne("id", department.getId()));
            for (SysDepartment sysDepartment : departmentList) {
                //查询医院的科室中，用户所填时间当天空闲的医生
                List<SysDoctor> doctorList = sysDoctorMapper.selectList(new QueryWrapper<SysDoctor>().eq("department_id", sysDepartment.getId()));
                if (doctorList != null && doctorList.size() > 0) {
                    for (SysDoctor doctor : doctorList) {
                        Long l = doctorRecordsMapper.selectCount(new QueryWrapper<SysDoctorRecords>().eq("doctor_id", doctor.getId())
                                .eq("visit_date", request.getVisitDate()));
                        if (l == 0) {
                            //不存在出诊记录则说明医生空闲
                            sysHospital = hospitalMapper.selectById(sysDepartment.getHospitalId());
                            doctor.setFullName(doctor.getName() + "-" + department.getName() + "-" + sysHospital.getName());
                            result.add(doctor);
                        }
                    }
                }
            }
        }
        if (result == null || result.size() == 0) {
            throw new ServiceException("没有找到符合条件的医生！");
        }
        return result;
    }

    private LambdaQueryWrapper<SysDoctor> buildWrapper(SysDoctorRequest param) {
        LambdaQueryWrapper<SysDoctor> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getName())) {
            query.like(SysDoctor::getName, param.getName());
        }
        if (StringUtils.isNotBlank(param.getSex())) {
            query.like(SysDoctor::getSex, param.getSex());
        }
        if (StringUtils.isNotBlank(param.getAge())) {
            query.like(SysDoctor::getAge, param.getAge());
        }
        if (param.getPostId() != null) {
            query.like(SysDoctor::getPostId, param.getPostId());
        }
        if (param.getDepartmentId() != null) {
            query.like(SysDoctor::getDepartmentId, param.getDepartmentId());
        }
        if (StringUtils.isNotBlank(param.getIsFree())) {
            query.like(SysDoctor::getIsFree, param.getIsFree());
        }
        return query;
    }

}
